# coding=utf8
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from tussin.books.models import Book
from django.template import RequestContext
from django.core.mail import send_mail

def search(request):
    errors = []
    if 'q' in request.GET:
        q = request.GET['q']
        if not q:
            errors.append('请输入查询关键字')
        elif len(q) > 20:
            errors.append('关键字不能超过20个字哦')
        else:
            books = Book.objects.filter(title__icontains=q)
            return render_to_response('search_results.html', {'books': books, 'query': q})
    return render_to_response('search_form.html', {'errors': errors})

def contact(request):
    errors = []
    if request.method == 'POST':
        if not request.POST.get('subject', ''):
            errors.append('请输入标题')
        if not request.POST.get('message', ''):
            errors.append('请输入留言')
        if request.POST.get('email') and '@' not in request.POST['email']:
            errors.append('请输入有效的邮件地址')

        if not errors:
            send_mail(
                request.POST['subject'], 
                request.POST['message'], 
                request.POST.get('email', 'noreply@example.com'),
                ['siteowner@example.com'],
            )
            return HttpResponseRedirect('/contact/thanks/')
    initData = {
        'errors': errors, 
        'subject': request.POST.get('subject', ''),
        'message': request.POST.get('message', ''),
        'email': request.POST.get('email', ''),}
    context = RequestContext(request)
    return render_to_response('contact_form.html', initData, context)
